package com.zijidelu.luframework.infrastructure.persistence.repository.core.criteria;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.zijidelu.luframework.base.bizsig.BizSignature;
import com.zijidelu.luframework.base.model.DataModel;
import com.zijidelu.luframework.base.model.PO;
import com.zijidelu.luframework.infrastructure.persistence.repository.core.data.DataRepository;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.Iterator;

/**
 * 基于 Mybatis Plus 的 业务签名数据仓库实现类。
 *
 * @author ZIJIDELU
 * @datetime 2025/10/20 16:37
 */
public abstract class AbstractBizSigPersistenceContext<P extends PO, D extends DataModel> implements BizSigPersistenceContext<P, D> {

    @Setter(onMethod_ = {@Autowired})
    private ObjectProvider<DataRepository<P, D>> dataRepositoryProvider;
    private DataRepository<P, D> dataRepository;

    public DataRepository<P, D> getDataRepository() {
        if (dataRepository == null) {
            dataRepository = dataRepositoryProvider.getIfAvailable();
        }
        return dataRepository;
    }

    @Override
    public QueryWrapper<P> buildBizSigQuery(BizSignature<D> bizSignature, D dto) {
        QueryWrapper<P> baseQueryWrapper = getDataRepository().getPersistenceContext().getBaseQueryWrapper();
        // 匹配业务签名
        bizSignature.validateBizSignatureAndConsume(
                dto,
                (k, v) -> baseQueryWrapper.eq(k.getFieldName(), v)
        );
        return baseQueryWrapper;
    }

    @Override
    public QueryChainWrapper<P> buildBizSigQueryChain(BizSignature<D> bizSignature, D dto) {
        final QueryChainWrapper<P> baseQueryChainWrapper = getDataRepository().getPersistenceContext().getBaseQueryChainWrapper();
        // 匹配业务签名
        bizSignature.validateBizSignatureAndConsume(
                dto,
                (k, v) -> baseQueryChainWrapper.eq(k.getFieldName(), v)
        );
        return baseQueryChainWrapper;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public LambdaQueryChainWrapper<P> buildBizSigLambdaQueryChain(final BizSignature<D> bizSignature, final D dto) {
        return buildBizSigQueryChain(bizSignature, dto).lambda();
    }

    @Override
    public UpdateChainWrapper<P> buildBizSigUpdateChain(BizSignature<D> bizSignature, D dto) {
        // 更新查询器
        final UpdateChainWrapper<P> baseUpdateChainWrapper = getDataRepository().getPersistenceContext().getBaseUpdateChainWrapper();
        // 匹配业务签名
        bizSignature.validateBizSignatureAndConsume(
                dto,
                (k, v) -> baseUpdateChainWrapper.eq(k.getFieldName(), v)
        );

        return baseUpdateChainWrapper;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public LambdaUpdateChainWrapper<P> buildBizSigLambdaUpdateChain(final BizSignature<D> bizSignature, final D dto) {
        return buildBizSigUpdateChain(bizSignature, dto).lambda();
    }

    @Override
    public QueryChainWrapper<P> buildPreciseBizSigQueryChain(BizSignature<D> bizSignature, Collection<D> dataColl) {
        if (CollectionUtils.isEmpty(dataColl)) {
            throw new IllegalArgumentException("dataColl is empty");
        }

        final QueryChainWrapper<P> baseQueryChainWrapper = getDataRepository().getPersistenceContext().getBaseQueryChainWrapper();

        final Iterator<D> iterator = dataColl.iterator();

        // 1. 处理第一个记录，构建初始的AND条件
        final D firstData = iterator.next();
        bizSignature.validateBizSignatureAndConsume(firstData,
                (k, v) -> baseQueryChainWrapper.eq(k.getFieldName(), v));

        // 2. 循环处理剩余记录，全部追加为OR条件
        // 整个循环体内没有任何条件判断
        while (iterator.hasNext()) {
            final D nextData = iterator.next();
            baseQueryChainWrapper.or(
                    wrapper -> bizSignature.validateBizSignatureAndConsume(nextData,
                            (k, v) -> wrapper.eq(k.getFieldName(), v)));
        }

        return baseQueryChainWrapper;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public LambdaQueryChainWrapper<P> buildPreciseBizSigLambdaQueryChain(BizSignature<D> bizSignature, Collection<D> dataColl) {
        return buildPreciseBizSigQueryChain(bizSignature, dataColl).lambda();
    }

    @Override
    public QueryChainWrapper<P> buildBizSigQueryChain(BizSignature<D> bizSignature, Collection<D> dataColl) {
        QueryChainWrapper<P> baseQueryChainWrapper = getDataRepository().getPersistenceContext().getBaseQueryChainWrapper();
        bizSignature.calcFieldNameGroupValues(dataColl).forEach(baseQueryChainWrapper::in);
        return baseQueryChainWrapper;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public LambdaQueryChainWrapper<P> buildBizSigLambdaQueryChain(BizSignature<D> bizSignature, Collection<D> dataColl) {
        return buildBizSigQueryChain(bizSignature, dataColl).lambda();
    }

}
